package com.diamond.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.UnauthenticatedException;
import org.codehaus.jackson.map.util.JSONPObject;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.diamond.core.entity.APIResult;
import com.diamond.core.entity.Result;
import com.diamond.core.feature.orm.hibernate.Page;
import com.diamond.core.util.ApplicationUtils;
import com.diamond.web.exceptions.AppException;

public abstract class GenericController{
	
	protected Logger log = Logger.getLogger(getClass());
	
	public String viewPath(){
		RequestMapping mapping = this.getClass().getAnnotation(RequestMapping.class);
		if(mapping!=null){
			return mapping.value()[0];
		}else{
			return "";
		}
	}
	
	public APIResult getSuccessResult(Object data){
		APIResult result = new APIResult();
		result.setSuccess(true);
		if(data instanceof List){
			result.setList((List<?>)data);
		}else{
			result.setData(data);
		}
		return result;
	}
	
	@ExceptionHandler(value=AppException.class)
	public void exceptionHandler(HttpServletResponse response,AppException ex) throws IOException{
		Result result = new Result();
		result.setMessage(ex.getMessage());
		result.setSuccess(false);
		String str = ApplicationUtils.Object2Json(result);
		log.error("AppException:"+str);
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(str);
	}

	@ExceptionHandler(value=UnauthenticatedException.class)
	public ModelAndView unauthenticatedException(UnauthenticatedException ex){
		ModelAndView mv = new ModelAndView();
		log.info("未登录，转跳到登录页面");
		mv.setViewName("admin/login_expires");
		return mv;
	}
	
	
	@ExceptionHandler
	public void otherExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception ex) throws IOException{
		log.info("Error Begin-------------------------------------");
		log.error(ex.toString());
		ex.printStackTrace();
		log.info("Error End-------------------------------------");
		request.setAttribute("errorType", ex.getClass().getName());
		request.setAttribute("error", ex.toString());
		response.sendError(500, ex.getClass().getSimpleName());
	}
	
	final public String viewPath(String path){
		String rootPath = viewPath();
		if(rootPath.endsWith("/")){
			return rootPath+viewPath();
		}
		return viewPath()+"/"+path;
	}
	
	final public ModelAndView getModelAndView(String path){
		ModelAndView mv = new ModelAndView();
		mv.setViewName(viewPath(path));
		return mv;
	}
	
	public HttpServletRequest getRequest(){
		return  ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); 
	}
	
	public HttpSession getSession(){
		return getRequest().getSession();
	}
	
	public Map<String,String> getParams(){
		HttpServletRequest request = getRequest();
		Map<String,String> params = new HashMap<String,String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = iter.next();
			String[] values =  requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		return params;
	}
	
	@SuppressWarnings("rawtypes")
	public Page<?> getPage(){
		Map<String,String> params = getParams();
		if(params.containsKey("pageSize")&&params.containsKey("pageNo")){
			Page<?> page = new Page(getInt("pageSize"),getInt("pageNo"));
			return page;
		}else{
			return null;
		}
	}
	public Integer getInt(String key){
		return getObject(key)==null?null:Integer.valueOf(getObject(key).toString());
	}
	public Long getLong(String key){
		return getObject(key)==null?null:Long.valueOf(getObject(key).toString());
	}
	public String getString(String key){
		return getObject(key)==null?null:String.valueOf(getObject(key));
	}
	public Object getObject(String key){
		return getParams().get(key);
	}
	public JSONPObject getJSONPObject(Object data){
		return new JSONPObject(getRequest().getParameter("callback"), data);
	}
	/**
	 * 将响应头设置为文件下载
	 * @param response 要设置的响应
	 * @param filename 返回到前端的文件名
	 */
	public void getFileDownloadResponse(HttpServletResponse response,String filename) {
		response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="+filename);		
	}
}
